<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 展示区 -->
      <tree-table :data="goodsCateList" :columns="columns" show-index border :expand-type="false"
        :selection-type="false">
        <!-- 是否有效 -->
        <template slot="isActive" slot-scope="scope">
          <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 分类等级 -->
        <template slot-scope="scope" slot="level">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="operation">
          <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[3, 5, 10, 15]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 添加分类对话框 -->
      <el-dialog title="提示" :visible.sync="addCateDialogVisible" width="40%" @close="addCateDialogClosed">
        <!-- 添加分类表单 -->
        <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRulesRef" label-width="100px">
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类：">
            <el-cascader v-model="selectKeys" :options="parentCateList" :props="cascaderProps" @change="parentCateChange" clearable collapse-tags>
            </el-cascader>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类数据总条数
      total: 0,
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        { label: '是否有效', type: 'template', template: 'isActive' },
        { label: '分类等级', type: 'template', template: 'level' },
        { label: '操作', type: 'template', template: 'operation' },
      ],
      goodsCateList: [],

      //添加分类对话框是否隐藏
      addCateDialogVisible: false,
      //添加分类表单数据对象
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      // 选中的分类的id
      selectKeys:[],
      //展示父级分类的数据列表
      parentCateList: [],
      // 级联选择器的配置对象
      cascaderProps: {
        checkStrictly: true,
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      }
    }
  },
  methods: {
    async getGoodsCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法获取商品分类数据')
      }
      this.goodsCateList = res.data.result
      this.total = res.data.total
      // console.log(this.goodsCateList)
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsCateList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsCateList()
    },

    //控制添加分类对话框函数
    showAddCateDialog() {
      this.getCateLevelList()
      this.addCateDialogVisible = true
    },
    //获取分类等级数据
    async getCateLevelList(){
      const {data: res} = await this.$http.get('categories', {params: {type:2,pagenum:5}})
      if(res.meta.status !== 200){
        return this.$message.error("请求服务器失败")
      }
      this.parentCateList = res.data
      // console.log(this.parentCateList)
    },
    //当级联选择框选中的值发生变化是调用
    parentCateChange(){
      //如果选中了父级分类则 selectKeys数组的长度大于0，反正则没选中任何父级
      if(this.selectKeys.length > 0){
        //父级分类id
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        //当前分类的层级
        this.addCateForm.cat_level = this.selectKeys.length
      }else{
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
      // console.log(this.addCateForm)
    },
    //发请求，添加分类
     addCate(){
      this.$refs.addCateFormRulesRef.validate(async valid =>{
        if(!valid) return
        
        const {data: res} = await this.$http.post('categories', this.addCateForm)
        if(res.meta.status !== 201){
          return this.$message.error("请求服务器失败，无法添加此分类信息")
        }
        this.addCateDialogVisible = false
        this.$message.success("添加分类信息成功")
        this.getGoodsCateList()
      })
    },
    addCateDialogClosed(){
      this.$refs.addCateFormRulesRef.resetFields()
      this.selectKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    }
  },
  created() {
    this.getGoodsCateList()
  },
}
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}
.el-cascader{
  width: 100%;
}

</style>>

